package com.github.pig.admin.controller.tsjy;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.tsjy.SuggestRecord;
import com.github.pig.admin.model.tsjy.SuggestRecordWhere;
import com.github.pig.admin.service.bindowner.BindOwnerService;
import com.github.pig.admin.service.tsjy.ISuggestRecordService;
import com.github.pig.admin.service.user.SysUserService;
import com.github.pig.admin.service.zhgl.community.ICommunityInfoService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 投诉建议记录表 前端控制器
 * </p>
 *
 * @author lxm
 * @since 2018-06-22
 */
@RestController
@RequestMapping("/suggestRecord")
public class SuggestRecordController extends BaseController {
    @Autowired
    private ISuggestRecordService suggestRecordService;
    @Autowired
    private ICommunityInfoService communityInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BindOwnerService bindOwnerService;


    /**
     * 分页查询信息-待受理记录
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params, SuggestRecordWhere suggestRecord, HttpServletRequest request) {
        EntityWrapper entityWrapper = new EntityWrapper<SuggestRecord>();
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO vo = bindOwnerService.selectUserVoByUsername(currentUserName);
        Page<SuggestRecord> page = new Page<SuggestRecord>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        //拼装条件
        initCondition(params, entityWrapper, suggestRecord, vo);

        entityWrapper.setSqlSelect("id, status,(select label from sys_dict where value=status and type='suggest_status') as statusName, owner_id AS ownerId,(select name from house_owner where id=owner_Id) as ownerName, house_id AS houseId,(select house_name from unit_house where id=house_Id) as houseName,suggest_time AS suggestTime, description, accept_time AS acceptTime, accept_user AS acceptUser,(select realname from sys_user where user_id=accept_user ) as acceptUserName, result_description AS resultDescription, del_flag AS delFlag, suggest_type,(select label from sys_dict where value=suggest_type and type='suggest_type') as suggestTypeName,(select unit_name from building_unit where id=unit_id) as unitName,(select building_name from community_building where id=building_id) as buildingName,(select name from community_info where id=community_id) as communityName");
        return suggestRecordService.selectPage(page, entityWrapper);
    }

    private void initCondition(Map<String, Object> params, EntityWrapper entityWrapper, SuggestRecordWhere suggestRecord, UserVO vo) {
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("community_id",suggestRecord.getCommunityId());
        //判断当前登陆人身份
        if(StringUtils.isBlank(vo.getType())||vo.getType().equals(CommonConstant.USER_TYPE_OWNER)){
            //业主 查看自己提交的记录
            entityWrapper.eq("owner_id",suggestRecord.getOwnerId());
        }else if(vo.getType().equals(CommonConstant.USER_TYPE_MANAGER)){
            //经理 可查看小区内所有投诉建议内容
//            if(CommonConstant.DONE.equals(suggestRecord.getType())){
//                //查看已办
//                entityWrapper.eq("accept_user",vo.getUserId());
//                entityWrapper.eq("status",CommonConstant.SUGGEST_STATUS_ACCEPT);
//            }if(CommonConstant.TO_DONE.equals(suggestRecord.getType())){
//                //查看待办记录
//                entityWrapper.eq("status","1");
//            }
        }else if(vo.getType().equals(CommonConstant.USER_TYPE_SERVICE)){
            //客服 查看提交的单据 和自己受理的单据
//            if(CommonConstant.DONE.equals(suggestRecord.getType())){
//                //查看已办记录
//                entityWrapper.eq("accept_user",vo.getUserId());
//                entityWrapper.eq("status",CommonConstant.REPAIR_STATUS_ACCEPT);
//            }else if(CommonConstant.TO_DONE.equals(suggestRecord.getType())){
//                //查看待办记录
//                entityWrapper.eq("status","0");
//            }
        }
        entityWrapper.orderBy("suggest_time",false);

    }

    /**
     * 显示受理详情
     *
     * @param suggestRecordId 实体
     * @return success/false
     */
    @RequestMapping("/toApprove")
    public SuggestRecord approve(String suggestRecordId) {

        return suggestRecordService.getSuggestRecordById(suggestRecordId);
    }

    /**
     * 受理
     *
     * @param suggestRecord 实体
     * @return success/false
     */
    @RequestMapping("/approve")
    public AjaxJson approve(@RequestBody SuggestRecord suggestRecord) {
        AjaxJson json = new AjaxJson();
        try {
            suggestRecord.setAcceptTime(new Date());
            Claims claims = getCurrentUserInfo();
            String currentUserName = (String) claims.get("user_name");
            UserVO userVO = sysUserService.findUserByUsername(currentUserName);
            suggestRecord.setAcceptUser(userVO.getUserId() + "");
            suggestRecord.setStatus(CommonConstant.SUGGEST_STATUS_ACCEPT);
            suggestRecordService.updateById(suggestRecord);
            json.setMsg("受理成功。");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("受理失败。");
            json.setSuccess(false);
            e.printStackTrace();
        }

        return json;
    }

    /**
     * 上报
     *
     * @param suggestRecordId 实体
     * @return success/false
     */
    @RequestMapping("/submitSug")
    public AjaxJson submitSug(String suggestRecordId) {
        AjaxJson json = new AjaxJson();
        try {
            List<SuggestRecord> suggestRecords = suggestRecordService.selectBatchIds(Arrays.asList(suggestRecordId.split(",")));
            for (SuggestRecord suggestRecord : suggestRecords) {
                suggestRecord.setStatus(CommonConstant.SUGGEST_STATUS_UPLOAD);
                suggestRecordService.updateById(suggestRecord);
            }
            json.setMsg("上报成功。");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("上报失败。");
            json.setSuccess(false);
            e.printStackTrace();
        }

        return json;
    }

    /**
     * 采纳
     *
     * @param suggestRecordId 实体
     * @return success/false
     */
    @RequestMapping("/accept")
    public AjaxJson accept(String suggestRecordId) {
        AjaxJson json = new AjaxJson();
        try {
            SuggestRecord suggestRecord = suggestRecordService.selectById(suggestRecordId);
            suggestRecord.setStatus("3");
            suggestRecordService.updateById(suggestRecord);
            json.setMsg("采纳成功。");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("采纳失败。");
            json.setSuccess(false);
            e.printStackTrace();
        }

        return json;
    }

    /**
     * 上传投诉/建议接口
     *
     * @param suggestRecord
     * @return
     */
    @PostMapping("/addSuggest")
    public AjaxJson addSuggest(@RequestBody SuggestRecord suggestRecord) {
        AjaxJson json = new AjaxJson();
        try {
            suggestRecord.setSuggestTime(new Date());
            suggestRecord.setDelFlag("0");
            suggestRecord.setStatus("0");
            suggestRecordService.insert(suggestRecord);
            json.setMsg("提交成功。");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("提交失败。");
            json.setSuccess(false);
            e.printStackTrace();
        }
        return json;
    }

    @DeleteMapping("/{id}")
    public AjaxJson delSuggest(@PathVariable String id) {
        AjaxJson json = new AjaxJson();
        try {
            SuggestRecord suggestRecord = new SuggestRecord();
            suggestRecord.setId(id);
            suggestRecord.setDelFlag("1");
            suggestRecordService.updateById(suggestRecord);
            json.setMsg("删除成功。");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("删除失败。");
            json.setSuccess(false);
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 分页查询信息
     *
     * @return 分页对象
     */
    @RequestMapping("/suggest/page")
    public Page suggestPage(@RequestParam Map<String, Object> params) {

        return suggestRecordService.suggestPage(params);
    }

    /**
     * 投诉/建议评价接口
     *
     * @param suggestRecord
     * @return
     */
    @PostMapping("/addEstimate")
    public AjaxJson addEstimate(@RequestBody SuggestRecord suggestRecord) {
        AjaxJson json = suggestRecordService.addEstimate(suggestRecord);

        return json;
    }

    /**
     * 投诉/建议查询接口
     *
     * @return
     */
    @GetMapping("/suggest/{id}")
    public AjaxJson querySuggest(@PathVariable String id) {
        return suggestRecordService.querySuggest(id);
    }
}
